package cn.tedu.repository.impl;

import cn.tedu.bo.WorkerCategoryBO;
import cn.tedu.dao.WorkerCategoryDao;
import cn.tedu.param.WorkerCategoryParam;
import cn.tedu.param.WorkerCreateParam;
import cn.tedu.repository.WorkerCategoryRepository;
import cn.tedu.repository.cache.impl.RedisCacheEntry;
import cn.tedu.repository.converter.WorkerCategoryConverter;
import com.tarena.tp.luban.worker.po.WorkerCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class WorkerCategoryRepositoryImpl extends RedisCacheEntry<WorkerCategoryBO> implements WorkerCategoryRepository {

    @Autowired
    private WorkerCategoryConverter workerCategoryConverter;
    @Autowired
    private WorkerCategoryDao workerCategoryDao;
    @Override
    public void deleteCategory(Long userId) {
        workerCategoryDao.delete(userId);
        //设置key值
        String key="luban:worker:category:"+userId;
        //删除缓存
        deleteCache(key);
    }

    @Override
    public void saveCategory(WorkerCreateParam workerCreateParam) {
        List<WorkerCategoryParam> workerCategoryParams = workerCreateParam.getWorkerCategoryParams();
        ArrayList<WorkerCategory> workerCategories = new ArrayList<>();
        for (WorkerCategoryParam workerCategoryParam : workerCategoryParams) {
            workerCategories.add(workerCategoryConverter.param2po(workerCategoryParam));
        }
        workerCategoryDao.insertCategories(workerCategories);
    }

    @Override
    public List<WorkerCategoryBO> findCategories(Long userId) {
        String key="luban:worker:category:"+userId;
        List<WorkerCategoryBO> categoryBOS;
        if (!exists(key)){
            List<WorkerCategory> workerCategories=workerCategoryDao.selectWorkerCategoriesByUserId(userId);
            categoryBOS = workerCategoryConverter.poList2BoList(workerCategories);
            saveCaches(key,categoryBOS);
        }else {
            categoryBOS=getCaches(key);
        }
        return categoryBOS;
    }
}
